<template>
    <div  class="chat-input-area">
        <div class="chat-input-area-wrapper" :class="{'is-disabled': loading}">
            <div class="chat-text-area textarea-resize-none">
                <div class="input-prefix-wrapper"></div>
                <textarea-autosize
                    class="chat-text-area-inner"
                    autofocus
                    rows="1"
                    placeholder="给政策咨询助手发送消息"
                    v-model="textareaInner"
                    @keydown.enter="enterSend"
                    :min-height="24"
                    :max-height="240"
                    ref="textarea">
                </textarea-autosize>
                <div part="input-actions-wrapper" class="actions-wrapper">
                    <div part="input-actions-extra" class="extra-actions-wrapper"></div>
                    <button part="button"
                        class="textarea-button"
                        :class="loading ? 'stop-btn' : 'send-btn'"
                        title="发送"
                        :disabled="disabled"
                        @click="send">
                        <svg v-if="!loading" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 22 20">
                            <path d="M1.12027 7.09484L4.61347 10.3216L13.5547 6.68564L6.79987 12.3052V17.6092C6.79987 17.687 6.82303 17.7629 6.86639 17.8275C6.90975 17.892 6.97135 17.9421 7.04333 17.9715C7.1153 18.0008 7.19439 18.0081 7.2705 17.9923C7.34662 17.9765 7.4163 17.9384 7.47067 17.8828L10.1107 15.1924L14.9995 19.7056C15.1019 19.8001 15.2268 19.8668 15.3623 19.8994C15.4977 19.932 15.6393 19.9294 15.7735 19.8919C15.9077 19.8544 16.03 19.7832 16.129 19.685C16.2279 19.5869 16.3001 19.4651 16.3387 19.3312L21.3631 1.85924C21.4122 1.68947 21.4152 1.50969 21.3717 1.33839C21.3283 1.16708 21.2401 1.01044 21.116 0.884561C20.992 0.758686 20.8366 0.668127 20.666 0.622197C20.4953 0.576268 20.3155 0.576627 20.1451 0.623237L1.46107 5.70764C1.32028 5.74568 1.19225 5.82076 1.09032 5.92506C0.988385 6.02936 0.916269 6.15908 0.881474 6.30071C0.846679 6.44234 0.850478 6.5907 0.892475 6.73037C0.934471 6.87003 1.01313 6.99589 1.12027 7.09484Z" fill="currentColor"></path>
                        </svg>
                        <svg v-else height="24" width="24" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
                            <path d="M392,432H120a40,40,0,0,1-40-40V120a40,40,0,0,1,40-40H392a40,40,0,0,1,40,40V392A40,40,0,0,1,392,432Z" fill="currentColor"></path>
                        </svg>
                    </button>
                
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { fetchEventSource } from '@microsoft/fetch-event-source';

export default {
    props: {
        list: {
            default: ()=> {[]},
            type: Array,
        }
    },
    data() {
        return {
            textareaInner: null,
            loading: false,
            ctrl: null,
        }
    },
    computed: {
        disabled() {
            return (!this.textareaInner || this.textareaInner.length === 0) && !this.loading
        },
    },
    methods: {
        enterSend() {
            if (!this.disabled) {
                this.send();
            }
        },
        send(){
            if (this.loading) {
                this.ctrl && this.ctrl.abort();
                this.loading = false;
                this.$emit('onMessage', '', 'system', this.loading);
            } else {
                this.$emit('updateList', this.textareaInner);
                this.textareaInner = null;
                this.startStream();
            }
            
        },
        async startStream() {
            const that = this;
            that.ctrl = new AbortController();
            await fetchEventSource('https://ark.cn-beijing.volces.com/api/v3/bots/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': 'Bearer b85f1d3f-b904-425c-8b28-eb0940bfe9e5'
                },
                body: JSON.stringify({
                    model: "bot-20250311172728-s5f4m",
                    stream:true,
                    stream_options:{
                        include_usage:true
                    },
                    messages: that.list
                }),
                signal: that.ctrl.signal,
                openWhenHidden: true,
                onopen(response) {
                    // 连接成功时触发
                    if (response.ok) {
                        that.loading = true;
                        that.$emit('updateList', '', 'system',);
                    } else {
                        that.ctrl = null;
                        throw new Error('连接失败');
                    }
                },
                onmessage(event) {
                    // 接收服务器发送的每条事件
                    if (event.data === '[DONE]') {
                        that.loading = false;
                        that.$emit('onMessage', '', 'system', that.loading);
                    } else {
                        const data = JSON.parse(event.data);
                        const content = (data.choices || []).reduce((acc, current)=> {
                            return acc += (current.delta.content || current.delta.reasoning_content || '')
                        }, '');
                        that.$emit('onMessage', content, 'system', that.loading);
                    }                    
                },
                onclose() {
                    // 连接关闭时触发
                    that.loading = false;
                    that.$emit('onMessage', '', 'system', that.loading);
                    console.log('连接终止');
                },
                onerror(err) {
                    // 错误处理（默认会抛出异常并自动重试）
                    console.error('错误:', err);
                    that.loading = false;
                    that.$emit('onMessage', '', 'system', that.loading);
                    throw err; // 抛出错误会触发重试机制
                }
            });
        }
    },
}
</script>
<style >
    .chat-input-area {
        flex-shrink: 0;
        margin: 10px 31.667PX;
    }
    .chat-input-area-wrapper:hover:not(.is-disabled),
    .chat-input-area-wrapper:focus-visible:not(.is-disabled),
    .chat-input-area-wrapper:focus-within:not(.is-disabled),
    .chat-input-area-wrapper:focus:not(.is-disabled) {
        box-shadow: rgb(134, 170, 255) 0px 1px 4px 0px, rgb(134, 170, 255) -1px -1px 4px 0px
    }

    .chat-input-area-wrapper {
        position: relative;
        box-shadow: rgba(25, 34, 52, 0.05) 0px 1px 4px 0px, rgba(90, 116, 255, 0.05) 0px 0px 24px 0px;
        border-radius: 24px;
    }
    .chat-text-area {
        position: relative;
        display: flex;
        align-items: center;
        cursor: text;
        width: 100%;
        box-sizing: border-box;
        min-height: var(--input-area-min-height, 48px);
        font-size: var(--input-area-font-size, 16px);
        background: var(--input-area-bg, #FFF);
        vertical-align: middle;
        padding: var(--input-area-padding);
        border: var(--input-area-border);
        color: var(--input-area-color);
        gap: var(--input-area-space);
        border-radius: var(--input-area-border-radius, 24px);
    }
    .input-prefix-wrapper {
        --space: calc(var(--input-area-actions-offset) - var(--input-area-space));
        margin: var(--space) 0 var(--space) var(--space);
        min-width: calc(var(--space)* -1);
    }
    .textarea-resize-none textarea {
        resize: none;
    }
    .chat-text-area-inner {
        flex: 1 1 auto;
        font-family: inherit;
        font-size: inherit;
        font-weight: inherit;
        line-height: var(--input-area-line-height);
        color: var(--input-area-color);
        padding: 0;
        border: none;
        background: none;
        box-shadow: none;
        cursor: inherit;
        max-height: var(--input-area-max-height);
        -webkit-appearance: none;
    }
    .actions-wrapper {
        position: absolute;
        right: var(--input-area-actions-offset);
        bottom: var(--input-area-actions-offset);
        display: inline-flex;
        align-items: center;
        justify-content: flex-end;
        gap: var(--input-area-actions-gap);
    }
    .extra-actions-wrapper {
        display: inline-flex;
        align-items: center;
        gap: var(--input-area-actions-gap);
    }
    .chat-text-area-inner:focus {
        outline: none;
    }
    .textarea-button[disabled] {
        cursor: not-allowed;
        background: var(--input-area-btn-bg-disabled);
        color: var(--input-area-btn-color-disabled);
    }

    .send-btn {
        background: var(--input-area-btn-bg);
    }
    .stop-btn {
        background: var(--input-area-btn-bg-stop);
    }
    .textarea-button {
        border: none;
        color: var(--input-area-btn-color);
        padding: 8px 10px;
        border-radius: var(--input-area-btn-border-radius);
        height: var(--input-area-btn-height);
        line-height: var(--input-area-line-height);
        cursor: pointer;
    }
</style>